<?php

namespace App\Http\Services;

use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Repositories\Daos\Task\EntrySurveyDao;
use App\Http\Repositories\Daos\Task\SweepDao;
use App\Http\Repositories\Daos\Team\TeamDao;
use App\Http\Repositories\Daos\Team\TeamUserDao;
use App\Http\Repositories\Redis\CacheDataRedis;
use App\Http\Requests\SignRequest;
use App\Http\Requests\UserContext;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class TaskService extends BaseService
{
    protected $sweepDao;
    protected $entrySurveyDao;
    protected $teamDao;
    protected $teamUserDao;

    public function __construct(SweepDao $sweepDao, EntrySurveyDao $entrySurveyDao, TeamDao $teamDao, TeamUserDao $teamUserDao)
    {
        $this->sweepDao       = $sweepDao;
        $this->entrySurveyDao = $entrySurveyDao;
        $this->teamDao        = $teamDao;
        $this->teamUserDao    = $teamUserDao;
    }

    public function lists()
    {
        $projectId = request('p_id') ?? '';
        $page      = request('page') ?? 1;
        $size      = request('size') ?? 10;
        $field     = ['id', 'project_id', 'user_id', 'team_id', 'sign_coord', 'sign_desc', 'sign_pics', 'updated_at'];
        $where     = [
            'project_id' => $projectId
        ];
        $order     = ['created_at' => 'desc'];
        $list      = $this->sweepDao->getListPage($where, $field, $page, $size, $order);
        if (!empty($list)) {
            foreach ($list as &$item) {
                $user                    = $item->userInfo;
                $item['nickname']        = $user->nickname;
                $item['avatar']          = $user->avatar;
                $entry_survey            = $item->entrySurvey;
                $item['entry_survey_id'] = $entry_survey ? $entry_survey['id'] : 0;
                unset($item->entrySurvey);
                unset($item->userInfo);
            }
            unset($item);
        }
        return $list;
    }

    public function sweepAdd(UserContext $userContext, SignRequest $signRequest)
    {
        $userId = $userContext->getId();
        $data   = $signRequest->validationData();
        $info   = $this->sweepDao->getOne(['id' => $data['id']]);
        if ($info && $info['user_id'] != $userId) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('扫街任务不存在或非自己创建'));
        }
        if (empty($info)) {
            unset($data['id']);
            $projectId          = $this->teamDao->getOneField(['id' => $data['team_id']], 'project_id');
            $data['user_id']    = $userId;
            $data['project_id'] = $projectId;
            $this->sweepDao->save($data);
            return true;
        }
        $info->fill($data);
        $info->save();
        return true;
    }

    public function entrySurveyGet(UserContext $userContext)
    {
        $id      = request('id') ?? 0;
        $userId  = $userContext->getId();
        $sweepId = request('sweep') ?? 0;
        if (empty($sweepId)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('选择扫街任务进行入户调研'));
        }
        $sweepInfo = $this->sweepDao->getOne(['id' => $sweepId]);
        if (empty($sweepInfo) || $sweepInfo['user_id'] != $userId) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('扫街任务不存在或非自己创建'));
        }
        if (empty($id)) {
            $info           = new \stdClass();
            $info->id       = 0;
            $info->sweep_id = (int)$sweepId;
            $info->content  = CacheDataRedis::getRedisInstance()->surveyTemplate();
            return $info;
        }
        $info = $this->entrySurveyDao->getOne(['id' => $id, 'sweep_id' => $sweepId]);
        if (empty($info)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('参数错误'));
        }
        return $info;
    }

    public function entrySurveySave(UserContext $userContext)
    {
        $id      = request('id') ?? 0;
        $userId  = $userContext->getId();
        $sweepId = request('sweep') ?? 0;
        $content = request('content') ?? '';
        Log::info('接收数据', ['data' => $content]);
        if (empty($sweepId)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('选择扫街任务进行入户调研'));
        }
        if (empty($content)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('调研内容为空'));
        }
        $sweepInfo = $this->sweepDao->getOne(['id' => $sweepId]);
        if (empty($sweepInfo) || $sweepInfo['user_id'] != $userId) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('扫街任务不存在或非自己创建'));
        }
        $info = $this->entrySurveyDao->getOne(['id' => $id, 'sweep_id' => $sweepId, 'user_id' => $userId]);
        if (empty($info)) {
            return $this->entrySurveyDao->save(['sweep_id' => $sweepId, 'user_id' => $userId, 'content' => $content]);
        }
        return $this->entrySurveyDao->update($id, ['content' => $content]);
    }

    public function teamSign()
    {
        $teamId    = request('team') ?? 0;
        $field     = ['id', 'team_id', 'user_id', 'sign_coord', 'sign_desc', 'sign_pics'];
        $list      = $this->sweepDao->getModel()->where('team_id', $teamId)->with(["userInfo" => function ($query) {
            $query->select(['id', 'nickname', 'avatar', 'mobile']);
        }])->orderBy('created_at', 'desc')->get($field);
        $team_info = $this->teamDao->getOne(['id' => $teamId], ['id', 'name', 'qty']);
        if (empty($team_info)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('队伍不存在'));
        }
        return compact("team_info", "list");
    }

    public function signDetail(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $id     = request('id') ?? 0;
        $field  = ['id', 'user_id', 'sign_coord', 'sign_desc', 'sign_pics'];
        $info   = $this->sweepDao->getModel()->where('id', $id)->where('user_id', $userId)->with(["userInfo" => function ($q) {
            $q->select(['id', 'nickname', 'avatar']);
        }])->first($field);
        if (empty($info)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('标记不存在'));
        }
        $entry_survey            = $info->entrySurvey;
        $info['entry_survey_id'] = $entry_survey ? $entry_survey['id'] : 0;
        unset($info->entrySurvey);
        return $info;
    }

    public function sweepDelete(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $id     = request('id') ?? 0;
        $info   = $this->sweepDao->getOne(['id' => $id, 'user_id' => $userId]);
        if (empty($info)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('标记不存在'));
        }
        DB::beginTransaction();
        try {
            $this->sweepDao->delete($id);
            $this->entrySurveyDao->deleteByWhere(['sweep_id' => $id, 'user_id' => $userId]);
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new ServiceException(ServiceExceptionConstant::getErrorData('删除标记失败'));
        }
    }

    public function teamPos(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $teamId = request('team') ?? 0;
        $field  = ['user_id', 'pos'];
        $list   = $this->teamUserDao->getModel()->where('team_id', $teamId)->where('pos', '!=', '')->orderBy('created_at', 'desc')->get($field);
//        $list      = $this->sweepDao->getModel()->where('team_id', $teamId)->orderBy('created_at', 'desc')->get($field);
        $team_info = $this->teamDao->getOne(['id' => $teamId], ['id', 'name', 'qty']);
        if (empty($team_info)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('队伍不存在'));
        }
        if (!empty($list)) {
            foreach ($list as &$item) {
                $userInfo       = $item->userInfo;
                $item['avatar'] = $userInfo['avatar'];
                unset($item->userInfo);
                $item['is_self'] = $item['user_id'] == $userId ? 1 : 0;
            }
            unset($item);
        }
        return compact("team_info", "list");
    }

}
